const Joi = require('joi');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const config = require('../config/config');

const User = require('../models/user.model');
const { databaseVersion } = require('../config/mysql');

module.exports = {
  generateToken,
  insert,
  findByUsername,
  findById,
}

const userInsertForm = Joi.object({
  username: Joi.string().required(),
  password: Joi.string().required(),
  name: Joi.string().default('your introduction'),
  avatar: Joi.string().default('https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'),
  introduction: Joi.string().default('your introduction'),
  roles: Joi.string().default('["editor"]'),
  createdAt: Joi.date().default(Date.now()),
  updatedAt: Joi.string().default(Date.now()),
})

function generateToken(user) {
  const payload = JSON.stringify(user);
  return 'Bearer '+jwt.sign(payload, config.jwtSecret);
}

async function insert(user) {
  user = await Joi.validate(user, userInsertForm, { abortEarly: false });
  user.password = bcrypt.hashSync(user.password, 10);
  const res = User.create(user);
  return res;
}

async function findByUsername(username) {
  const user = await User.findOne({
    where: {
      username: username
    }
  });
  if (user === null) {
    return false;
  } else {
    return user.dataValues;
  }
}

async function findById(id) {
  const user = await User.findOne({
    where: {
      id: id
    }
  });
  if (user === null) {
    return false;
  } else {
    return user.dataValues;
  }
}






